package com.sxfq.loansupermarket.backsystem.modular.theTest.controller;

import com.sxfq.loansupermarket.backsystem.common.annotion.log.BussinessLog;
import com.sxfq.loansupermarket.backsystem.common.constant.Const;
import com.sxfq.loansupermarket.backsystem.common.constant.Dict;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.ConstantFactory;
import com.sxfq.loansupermarket.backsystem.common.constant.tips.Tip;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.persistence.dao.UserMapper;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.User;
import com.sxfq.loansupermarket.backsystem.config.properties.GunsProperties;
import com.sxfq.loansupermarket.backsystem.core.log.LogObjectHolder;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroUser;
import com.sxfq.loansupermarket.backsystem.core.util.AliyunOssUtil;
import com.sxfq.loansupermarket.backsystem.core.util.DateUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.system.factory.UserFactory;
import com.sxfq.loansupermarket.backsystem.modular.system.transfer.UserDto;
import com.sxfq.loansupermarket.backsystem.modular.theTest.service.IUserService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.naming.NoPermissionException;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * 答题
 *
 * @author py
 * @Date 2018年2月4日23:05:54
 */
@Controller
@RequestMapping("/my")
public class MyController extends BaseController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    IUserService iUserService;

    @Autowired
    AliyunOssUtil aliyunOssUtil;

    @RequestMapping("")
    public String to_my(Model model) {
        Integer userId = ShiroKit.getUser().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        User user = this.userMapper.selectById(userId);
        if (user.getAvatar() == null || user.getAvatar() == "") {
            user.setAvatar("http://yiyayl.com/photo/logo.png");
        }
        int ranking = iUserService.getRanking(userId) + 1;
        model.addAttribute(user);
        model.addAttribute("roleName", ConstantFactory.me().getRoleName(user.getRoleid()));
        model.addAttribute("deptName", ConstantFactory.me().getDeptName(user.getDeptid()));
        LogObjectHolder.me().set(user);
        model.addAttribute("userName", user.getName());
        model.addAttribute("ranking", ranking);
        model.addAttribute("avatar", user.getAvatar());
        return "/theTest/my.html";
    }

    @RequestMapping("/myTest")
    public String to_myTest(Model model) {
        Integer userId = ShiroKit.getUser().getId();
        User user = userMapper.selectById(userId);
        model.addAttribute("userName", user.getName());
        model.addAttribute("theTestCount", iUserService.getTestCount(userId).get("theTestCount"));
        model.addAttribute("completeTestCount", iUserService.getTestCount(userId).get("completeTestCount"));
        model.addAttribute("incompleteTestCount", iUserService.getTestCount(userId).get("incompleteTestCount"));
        return "/theTest/myTest.html";
    }

    /**
     * 修改管理员
     *
     * @throws NoPermissionException
     */
    @RequestMapping("/edit")
    @BussinessLog(value = "修改管理员", key = "account", dict = Dict.UserDict)
    @ResponseBody
    public Tip edit(@Valid UserDto user, BindingResult result) throws NoPermissionException {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ShiroKit.hasRole(Const.ADMIN_NAME)) {
            this.userMapper.updateById(UserFactory.createUser(user));
            return SUCCESS_TIP;
        } else {
            ShiroUser shiroUser = ShiroKit.getUser();
            if (shiroUser.getId().equals(user.getId())) {
                this.userMapper.updateById(UserFactory.createUser(user));
                return SUCCESS_TIP;
            } else {
                throw new BussinessException(BizExceptionEnum.NO_PERMITION);
            }
        }
    }

    /**
     * 上传图片(上传到项目的webapp/static/img)
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile picture) {
//        String basePath = GunsProperties.PREFIX + "/upload/comPanyPic/" + DateUtil.format(new Date(), "yyyy-MM-dd") + "/";
//        String pictureName = UUID.randomUUID().toString() + ".jpg";
//        String remoteFilePath = null;
//        try {
//            String fileSavePath = basePath + pictureName;
//            aliyunOssUtil.pushSingleFile(picture, fileSavePath);
//            remoteFilePath = aliyunOssUtil.imgUrl() + fileSavePath;
//            UserDto user = new UserDto();
//            ShiroUser shiroUser = ShiroKit.getUser();
//            user.setId(shiroUser.getId());
//            user.setAvatar(remoteFilePath);
//            this.userMapper.updateById(UserFactory.createUser(user));
//        } catch (Exception e) {
//            throw new BussinessException(BizExceptionEnum.UPLOAD_ERROR);
//        }
//        return remoteFilePath;
//        String realPath = "D:\\wwwroot\\yiyayl\\wwwroot\\photo";
        String realPath = "D:\\20180409\\apache-tomcat-8.0.30\\webapps\\ROOT\\touxiang";
//        String FileInput = realPath + "\\" + picture.getOriginalFilename();
//        String httpUrl = "http://yiyayl.com/photo/";
        String httpUrl = "http://47.98.150.186/touxiang/";
        try {
            FileUtils.copyInputStreamToFile(picture.getInputStream(), new File(realPath, picture.getOriginalFilename()));
            UserDto user = new UserDto();
            ShiroUser shiroUser = ShiroKit.getUser();
            user.setId(shiroUser.getId());
            user.setAvatar(httpUrl + "\\" + picture.getOriginalFilename());
            this.userMapper.updateById(UserFactory.createUser(user));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return realPath;
    }

    @RequestMapping("/personalCentres")
    public String to_personalCentres(Model model) {
        Integer id = ShiroKit.getUser().getId();
        User user = userMapper.selectById(id);
        model.addAttribute("userName", user.getName());
        return "/theTest/personalCentres.html";
    }

    @RequestMapping("/updatePersonal")
    public String to_updatePersonal(Model model) {
        Integer id = ShiroKit.getUser().getId();
        User user = userMapper.selectById(id);
        model.addAttribute("user", user);
        return "/theTest/updatePersonal.html";
    }

    @RequestMapping("/toUpdatePassWord")
    public String to_updatePassWord(Model model) {
        Integer id = ShiroKit.getUser().getId();
        User user = userMapper.selectById(id);
        model.addAttribute("orPassWord", user.getPassword());
        return "/theTest/updatePassWord.html";
    }

//    @RequestMapping(value = "/getTestCount", method = RequestMethod.GET)
//    @ResponseBody
//    public Map<String, Object> getTestCount(Model model) {
//        Object theTestCount = iUserService.getTestCount().get("theTestCount");
//        Object completeTestCount = iUserService.getTestCount().get("completeTestCount");
//        Object incompleteTestCount = iUserService.getTestCount().get("incompleteTestCount");
//        return iUserService.getTestCount();
//    }

    /**
     * 修改考试
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public int update(@Valid User entity, BindingResult result) throws Exception {
        int nameCount = iUserService.selectSameNameCountForUpdate(entity.getId(), entity.getName());
        if (nameCount > 0) {
            return 0;
        } else {
            if (result.hasErrors()) {
                throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
            }
            iUserService.UpdateWithInfo(entity);
            return 1;
        }
    }

    @RequestMapping(value = "/updatePassWord", method = RequestMethod.POST)
    @ResponseBody
    public String updatePassWord() {
        Integer id = ShiroKit.getUser().getId();
        User user = userMapper.selectById(id);
        String newPassWord = super.getPara("newPassWord").trim();
        String passWord = super.getPara("passWord").trim();
        String passWordMd5 = ShiroKit.md5(passWord, user.getSalt());
        if (passWordMd5.equals(user.getPassword())) {
            String newPassWordMd5 = ShiroKit.md5(newPassWord, user.getSalt());
            user.setPassword(newPassWordMd5);
            userMapper.updateById(user);
            return "0";
        } else {
            return "1";
        }
    }

}
